/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jsonHelper.SimpleStepTwo;
import jsonHelper.SimpleTag;
import service.Planet;
import service.PlanetFacadeREST;
import service.Tag;
import service.TagFacadeREST;
import service.Universe;
import service.UniverseFacadeREST;

/**
 *
 * @author andrew
 */
@WebServlet(name = "secondStepServlet", urlPatterns = {"/secondStepServlet"})
public class secondStepServlet extends HttpServlet {

    @EJB
    private PlanetFacadeREST planetManager;
    @EJB
    private UniverseFacadeREST universeManager;
    @EJB
    private TagFacadeREST tagManager;
    private static int WIDTH_VIEW = 1000;
    private static int HEIGHT_VIEW = 480;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //HttpSession session = request.getSession();
        // check if session is expired
        HttpSession session = request.getSession();// don't create if it doesn't exist
//        if(session != null && !session.isNew()) {} 
//        else {
//            response.sendRedirect("/home.jsp");
//        }

        Gson gson = new Gson();
        SimpleStepTwo myObj = new SimpleStepTwo();

        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        String editingPlanetIdString = request.getParameter("editingPlanetId");
        String editingUniverseIdString = request.getParameter("editingUniverseId");

        int editingPlanetId = Integer.parseInt(editingPlanetIdString);
        int editingUniverseId = Integer.parseInt(editingUniverseIdString);


        if (editingPlanetId == -1) {


            // form vuote per presentazione
            myObj.setIdPlanet(editingPlanetId);
            myObj.setFirstRow("");
            myObj.setSecondRow("");
            myObj.setThirdRow("");
            myObj.setShortLabel("");
            myObj.setDescriptionPlanet("");
            myObj.setArrayTag(new ArrayList<SimpleTag>());

            // editingPlanetId = newIdPlanet;

        } else {
            // form popolate perché si modifica un pianeta
            editingPlanetId = Integer.parseInt(editingPlanetIdString);

            // prendo pianeta con ID specificato
            Planet planet = planetManager.find(editingPlanetId);

            myObj.setFirstRow(planet.getTitle1());
            myObj.setSecondRow(planet.getTitle2());
            myObj.setThirdRow(planet.getTitle3());
            myObj.setShortLabel(planet.getShortLabel());
            myObj.setDescriptionPlanet(planet.getDescription());

            Collection<Tag> collTag = planet.getTagCollection();

            ArrayList<SimpleTag> tempArray = new ArrayList<SimpleTag>();

            Iterator iterator = collTag.iterator();
            while (iterator.hasNext()) {
                Tag tag = (Tag) iterator.next();
                SimpleTag simpleTag = new SimpleTag();
                simpleTag.setIdTag(tag.getIdTag());
                simpleTag.setTagValue(tag.getDescription());
                tempArray.add(simpleTag);
            }
            myObj.setArrayTag(tempArray);
        }

        // inserire in sessione id pianeta che si sta manipolando
        session.setAttribute("idPlanet", editingPlanetId);


        String StringToClient = gson.toJson(myObj);
        // restituzione JSON
        out.print(StringToClient);
        out.close();
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        
        // si prende il pianeta con ID passato
        //System.out.print("valore ID = "+idPlanet);
        String idPlanetString = request.getParameter("editingPlanetId");
        //System.out.println("Can del porco string = "+idPlanetString);
        Integer editingUniverseId = (Integer)session.getAttribute("idUniverse");
        
        int idPlanet = Integer.parseInt(idPlanetString);
        
        String emotionalChooseStr = request.getParameter("emotionalChoose");
        
        System.out.println("Valore ID universo = "+editingUniverseId);
        

        if (idPlanet == -1 && emotionalChooseStr == null) {
            // creo nuovo pianeta
            Planet newPlanet = new Planet();
            // imposto propriet√† iniziali vuote
            newPlanet.setTitle1(" ");
            newPlanet.setTitle2("");
            newPlanet.setTitle3(" ");
            newPlanet.setShortLabel(" ");
            newPlanet.setDescription(" ");
            newPlanet.setAddress(" ");
            newPlanet.setZipCode(" ");
            newPlanet.setProvince(" ");
            newPlanet.setMunicipality(" ");
            newPlanet.setControlled(0);
            newPlanet.setEmotionalFilter(0);
            
            // setto coordinate da visualizzare su connessioni
            Random r = new Random();
            
            int x = Math.abs(r.nextInt(WIDTH_VIEW)) % WIDTH_VIEW;
            int y = Math.abs(r.nextInt(HEIGHT_VIEW)) % HEIGHT_VIEW;
            
            newPlanet.setCoordinatePositionX(x);
            newPlanet.setCoordinatePositionY(y);
            
            Universe universe = universeManager.find(editingUniverseId);
            newPlanet.setUniverseidUniverse(universe);
            newPlanet.setReferenceName(" ");           
            
            // prendo i pianeti associati all'universo gi√† creati
            Collection<Planet> collPlanet = universe.getPlanetCollection();
            
            
            
            // aggiungo il nuovo pianeta appena creato alla lista dei pianeti dell'universo
            collPlanet.add(newPlanet);
           
            // aggiurno la lista associata all'universo
            universe.setPlanetCollection(collPlanet);
            // persistenza in db
            universeManager.edit(universe);
            
            List<Planet> planetList = planetManager.findAll();
            Iterator<Planet> planetIt = planetList.iterator();
            Planet tmpPlanet;
            while(planetIt.hasNext()){
                tmpPlanet = planetIt.next();
                if(tmpPlanet.getTitle1().equals(" ")){
                    idPlanet = tmpPlanet.getIdPlanet();
                    session.setAttribute("idPlanet", idPlanet);
                }
            }
            
            //idPlanet = newPlanet.getIdPlanet();
            
            System.out.println("Valore idPlanet = "+idPlanet);
            
        }
        
        if(idPlanet == -1){
            idPlanet = (Integer)session.getAttribute("idPlanet");
        }
        
        Planet planet = planetManager.find(idPlanet);
        
        //System.out.println("Pianeta pescato = "+idPlanet);




        emotionalChooseStr = request.getParameter("emotionalChoose");
        if (emotionalChooseStr != null) {
            //System.out.println("Porca troia che titoeo: "+emotionalChooseStr);
            Integer emotionalChoose = Integer.parseInt(emotionalChooseStr);
            //System.out.println("Cantante leamaro: "+emotionalChoose);
            planet.setEmotionalFilter(emotionalChoose);
        } else {
            
            String title1 = request.getParameter("title1");
            String title2 = request.getParameter("title2");
            String title3 = request.getParameter("title3");
            String shortLabel = request.getParameter("shortLabel");
            String descPlanet = request.getParameter("description");

            // si popola l'oggetto con le nuove modifiche apportate
            planet.setTitle1(title1);
            planet.setTitle2(title2);
            planet.setTitle3(title3);
            planet.setShortLabel(shortLabel);
            planet.setDescription(descPlanet);
            planet.setControlled(0);


        }
        // si aggiorna in db
        planetManager.edit(planet);

        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        // invia come risposta il valore di emotional filter
        System.out.println(planet.getEmotionalFilter());
        
        out.print(planet.getIdPlanet()+"-"+planet.getEmotionalFilter());
        out.close();
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
